import {ParamsType} from "@ant-design/pro-components";
import {ResponseStructure} from "@/requestErrorConfig";
import {request} from "umi";

// 默认 API 前缀，可以根据环境修改
const API_BASE_URL = "/api"; // 可修改为 "/test-api" 之类的

/**
 * API 请求接口（普通 TS 代码也能使用）
 *
 * @author 橘柚
 * @Date 2025/3/18 17:20
 * @Description 适用于所有 API 模块（如 /customer, /order, /product）
 */
interface IApiService {
  get: (endpoint: string, params?: ParamsType, options?: DynamicObject) => Promise<ResponseStructure>;
  pageData: (params?: ParamsType, options?: DynamicObject) => Promise<ResponseStructure>;
  listData: (params?: ParamsType, options?: DynamicObject) => Promise<ResponseStructure>;
  addData: <T>(data: T, options?: DynamicObject) => Promise<ResponseStructure>;
  updateById: <T>(data: T, options?: DynamicObject) => Promise<ResponseStructure>;
  deleteById: (id: string | number, options?: DynamicObject) => Promise<ResponseStructure>;
}

/**
 * 创建 API 工具
 * @param baseUrl API 基础路径
 * @param apiPrefix API 前缀
 * @returns 该路径下的所有请求方法
 */
export const createApiService = (baseUrl: string, apiPrefix: string = API_BASE_URL): IApiService => {
  return {
    get: async (endpoint: string, params?: ParamsType, options?: DynamicObject) => {
      return request<ResponseStructure>(`/${apiPrefix}/${baseUrl}${endpoint}`, {
        method: "GET",
        params: {...params},
        ...(options || {}),
      });
    },

    pageData: async (params?: ParamsType, options?: DynamicObject) => {
      return request<ResponseStructure>(`/${apiPrefix}/${baseUrl}/page`, {
        method: "GET",
        params: {...params},
        ...(options || {}),
      });
    },

    listData: async (params?: ParamsType, options?: DynamicObject) => {
      return request<ResponseStructure>(`/${apiPrefix}/${baseUrl}/list`, {
        method: "GET",
        params: {...params},
        ...(options || {}),
      });
    },

    addData: async <T>(data: T, options?: DynamicObject) => {
      return request<ResponseStructure>(`/${apiPrefix}/${baseUrl}`, {
        method: "POST",
        data,
        ...(options || {}),
      });
    },

    updateById: async <T>(data: T, options?: DynamicObject) => {
      return request<ResponseStructure>(`/${apiPrefix}/${baseUrl}/updateById`, {
        method: "PUT",
        data,
        ...(options || {}),
      });
    },

    deleteById: async (id: string | number, options?: DynamicObject) => {
      return request<ResponseStructure>(`/${apiPrefix}/${baseUrl}/${id}`, {
        method: "DELETE",
        ...(options || {}),
      });
    },
  };
};
